package com.oig.sys.query.support.module;


import com.alibaba.fastjson.annotation.JSONField;
import com.oig.common.constants.CommonConstants;
import com.oig.sys.query.constants.ExpressionEnum;
import lombok.Data;

import java.util.List;

/**
 * {
 *     "fields": [
 *          {"field": "t1.id", "rename": "id", "cnname": "库存id", "options": {"dataType": "int"}},
 *     ],
 *     "tables": [
 *          {"field": "stock", "rename": "t1", "join": "master", "on": ""},
 *     ],
 *     "group_by": [
 *     ]
 * }
 */
@Data
public class QueryExpression {

    private List<FieldExpression> fields;
    private List<TableExpression> tables;
    @JSONField(name = "group_by")
    private List<String> groupBy;

    @JSONField(name = "order_by")
    private List<SortExpression> orderBy;

    public String getTableField(String fieldName) {
        for (FieldExpression fc : this.fields) {
            if (fc.getRename().equals(fieldName)) {
                //可能后续考虑 json加个属性来配置查询条件比较好
                if (fc.getField().contains(CommonConstants.LEFT_PARENTHESIS)){
                    String fcField=fc.getField().substring(fc.getField().lastIndexOf(CommonConstants.LEFT_PARENTHESIS)+1,fc.getField().indexOf(CommonConstants.RIGHT_PARENTHESIS));
                    if (fcField.startsWith(ExpressionEnum.S_DIS)||fcField.contains(ExpressionEnum.S_DIS)){
                        fcField = fcField.replace(ExpressionEnum.S_DIS,"") ;
                    }
                    if (fcField.startsWith(ExpressionEnum.S_DIS.toUpperCase())||fcField.contains(ExpressionEnum.S_DIS.toUpperCase())){
                        fcField = fcField.replace(ExpressionEnum.S_DIS.toUpperCase(),"") ;
                    }
                    return fcField;
                } else {
                    return fc.getField();
                }
            }
        }
        return null;
    }
}
